<template>
  <view>
    <Table ref="table" :fetchData="fetchData" :autoFetch="false">
      <template #default="{ data }">
        <view v-for="item in data">
          <uni-card @click="onCardClick(item)">
            <view class="uni-body">
              <view class="title">
                <view class="title-left">
                  <view class="title-title">
                    {{ item.specialNumber }}
                  </view>
                  <span class="title-times">
                    {{ zypTypes[item.jobType] }}
                  </span>
                  <view
                    class="title-state"
                    :style="{
                      backgroundColor: `${item.color} !important`,
                      color: item.fontColor,
                    }"
                  >
                    {{ item.state }}
                  </view>
                </view>
              </view>
              <view>
                {{ item.data.zynr || item.data.jobContent }}
              </view>
              <view
                style="
                  font-size: 12px;
                  display: flex;
                  justify-content: space-between;
                  width: 100%;
                "
              >
                <text style="color: orange">
                  {{ item.jobStartDate }}
                </text>
                <text style="flex: end">
                  {{ item.data.zydw }}
                </text>
              </view>
              <view
                style="
                  display: flex;
                  justify-content: flex-end;
                  margin-top: 10upx;
                "
              >
                <button
                  type="primary"
                  size="mini"
                  style="width: 35%"
                  @click.stop="onFuzhi(item)"
                  v-hasPermi="['zyp-copy']"
                >
                  复 制
                </button>
                <button
                  type="warn"
                  size="mini"
                  style="width: 35%"
                  @click.stop="onZuofei(item)"
                  v-hasPermi="['zyp-zf']"
                >
                  作 废
                </button>
              </view>
            </view>
          </uni-card>
        </view>
      </template>
    </Table>

    <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
      <view class="popup">
        <view class="mTitle">作废原因</view>
        <view class="bd">
          <uni-easyinput type="text" style="width: 200upx;" v-model="ynReason" placeholder="请输入" />
        </view>
        <view class="ft">
          <view class="btn" @click="fConfirm">确定</view>
          <view class="btn" @click="fCancel">取消</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>
<script>
export default {
  data() {
    return {
      pid: "",
      billType: "",
      fid: "",
      zypTypes: {
        1: "吊装安全作业票",
        2: "动火安全作业票",
        3: "高处安全作业票",
        4: "动土安全作业票",
        5: "临时用电安全作业票",
        6: "动用射线安全作业票",
        7: "断路安全作业票",
        8: "盲板抽堵安全作业票",
        9: "设备开孔安全作业票",
        10: "受限空间安全作业票",
      },
    };
  },
  onLoad(payload) {
    this.pid = payload.pid;
    this.fid = payload.id;
  },
};
</script>
<script setup>
import { ref, onActivated, onMounted, getCurrentInstance } from "vue";
import Table from "@/components/uniList.vue";
import { useAsyncData } from "@/hooks/useAsyncData.js";
import { apis as APIS } from "@/api/zygl/zyp.js";
import { router } from "@/router/index.js";
import { PATH } from "../paths";
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import zyp, { qmlc } from "./options/index.js";

const popup = ref();

const formatList = (rows) => {
  return rows.map((item) => {
    let content = JSON.parse(item.content);
    if (!content.jsjdr || content.jsjdr.length == 0) {
      content.jsjdr = [];
      if (content.jsjdr1) {
        content.jsjdr.push(content.jsjdr1);
      }
    }
    let row = {
      ...item,
      data: content,
    };
    return {
      ...row,
      ...getSplc(row),
    };
  });
};
const onCardClick = (item) => {
  router.toPage({
    path: PATH.ZYP,
    // path: item.jobType == 2 ? PATH.ZYPV2 : PATH.ZYP,
    params: {
      id: item.id,
      pid: FID.value,
      billNumber: filterForm.value.ptw,
    },
  });
};

const table = ref();
const filterForm = ref({});
const { fetchData, getList, queryParams } = useAsyncData({
  table,
  APIS,
  filterForm: filterForm.value,
  formatList,
});
const FID = ref("");
onShow(() => {
  const { pid, fid } = getCurrentInstance().data;
  filterForm.value.ptw = pid;
  FID.value = fid;
  getList();
});
onMounted(() => {
  const { pid, fid } = getCurrentInstance().data;
  filterForm.value.ptw = pid;
  FID.value = fid;
  getList();
});


const id = ref(null)
const ynReason = ref('')

const onZuofei = (row) => {
  popup.value.open("center");
  id.value = row.id
  ynReason.value = ''
  // uni.showModal({
  //   title: "提示",
  //   content: `是否确认作废该作业票?`,
  //   success: function (res) {
  //     if (res.confirm) {
  //       APIS.del({
  //         id: row.id,
  //       }).then((res) => {
  //         getList();
  //       });
  //     } else if (res.cancel) {
  //     }
  //   },
  // });
};

const fCancel = () => {
  popup.value.close();
}

const fConfirm = () => {
  console.log('ynReason.value:', ynReason.value, ynReason.value == '')
  if(ynReason.value == ''){
    return uni.showToast({
      title: '请输入作废原因！',
      icon: 'none'
    });
  }
  APIS.del({
    id: id.value,
    ynReason: ynReason.value
  }).then((res) => {
    if(res){
      console.log('uni.showToast', uni.showToast)
      
      uni.showToast({
        title: '提交成功！',
        icon: 'success',
        duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
        mask: false // 是否显示透明蒙层，防止触摸穿透，默认：false
      });
      setTimeout(() => {
        console.log('提交成功！')
        popup.value.close();
        getList();
      }, 2000);
    }
  });
}

const onFuzhi = (row) => {
  uni.showModal({
    title: "提示",
    content: `是否确认复制该作业票?`,
    success: function (res) {
      if (res.confirm) {
        const options = zyp[row.jobType];
        let data = {};
        const content = row.content;
        if (content) {
          data = JSON.parse(content);
        }
        if (options) {
          options.emptys.forEach((item) => {
            data[item] = null;
          });
        }
        data.qitiData = [];
        data.jobDate = ["", ""];
        APIS.copy({
          content: JSON.stringify(data),
          id: row.id,
        }).then((res) => {
          getList();
        });
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

const getSplc = (data) => {
  let lcList = qmlc[data.jobType];
  let jsjdr = data.data.jsjdr;
  if (jsjdr && jsjdr.length) {
    if (jsjdr instanceof Array) {
      jsjdr = jsjdr.filter((ele) => ele);
    } else {
      jsjdr = [jsjdr];
    }
  } else {
    jsjdr = [];
  }
  const content = {
    ...data.data,
    jsjdr,
  };
  // const jobDate = content.jobDate;
  // if (jobDate && jobDate[1]) {
  //   let endTime;
  //   let now = Date.now();
  //   try {
  //     endTime = new Date(jobDate[1]);
  //     endTime = endTime.getTime();
  //   } catch (e) {}

  //   if (endTime < now) {
  //     return {
  //       state: "已关闭",
  //       color: "rgb(226,240,217)",
  //       fontColor: "rgb(0,176,80)",
  //     };
  //   }
  // }

  if (!lcList) {
    return null;
  }
  if ([1, 2, 3].includes(Number(data.jobType))) {
    let jb = content.dhzyjb || content.Grade || content.zyjb || null;
    if (!jb) {
      lcList = [];
    }
    if (data.jobType == 2) {
      lcList = jb.includes("二级") ? lcList.ej : lcList.yj;
    }

    if (data.jobType == 1) {
      lcList = jb.includes("一级") ? lcList.yj : lcList.ej;
    }
    if (data.jobType == 3 && jb.includes("Ⅰ级")) {
      lcList = lcList.yj;
    } else if (data.jobType == 3) {
      lcList = jb.includes("Ⅳ级") ? lcList.sj : lcList.ej;
    }
  }

  if (lcList.length) {
    let index = 0;
    let flag = true;
    let state = "";
    let prop = "";
    let color = "";
    let fontColor = "";

    while (index < lcList.length && flag) {
      const element = lcList[index];
      if (element.prop == "aqjdr") {
        flag = content.aqjdr && content.jsjdr && content.jsjdr.length > 0;
        console.log(content);
      } else if (element.prop == "qitiData") {
        flag =
          content.qitiData &&
          content.qitiData.length > 0 &&
          content.qitiData.every((ele) => ele.fxr);
      } else if (data.jobType == 4 && element.prop == "yjqm3") {
        flag = content.yjqm3.length > 0;
      } else {
        flag = !!content[element.prop];
      }
      if (!flag) {
        state = element.name;
        color = element.color;
      }
      index++;
    }
    if (index === lcList.length && flag) {
      state = "已关闭";
      color = "rgb(226,240,217)";
    }
    switch (color) {
      case "rgb(226,240,217)":
        fontColor = "rgb(0,176,80)";
        break;
      case "rgb(215,232,246)":
        fontColor = "rgb(46,117,182)";
        break;
      case "rgb(248,240,235)":
        fontColor = "rgb(197,90,17)";
        break;
      case "rgb(250,217,217)":
        fontColor = "rgb(255,0,0)";
        break;
      default:
        break;
    }
    console.log({
      state,
      color,
      fontColor,
    });
    return {
      state,
      color,
      fontColor,
    };
    // return {
    //   state: null,
    //   color: "#fff",
    //   fontColor: "#fff",
    // };
  } else {
    return null;
  }
};
</script>

<style lang="scss" scoped>
.button-box {
  // display: flex;
  position: relative;
  flex-wrap: wrap;
  justify-content: start;
  .mini-btn {
    margin: 0 5rpx;
  }
}
.close {
  position: absolute;
  top: -5rpx;
  right: -25rpx;
  color: skyblue !important;
}
.title {
  display: flex;
  justify-content: space-between;
  position: relative;

  &-left {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  }
  &-title {
    font-weight: 600;
  }
  &-times {
    background-color: rgb(22, 119, 255);
    padding: 2px;
    font-size: 12px;
    line-height: 15px;
    border-top-left-radius: 10px;
    border-bottom-right-radius: 10px;
    margin-left: 5px;
    color: #fff;
  }
  &-state {
    // background-color: orange;
    position: absolute;
    right: 0;
    padding: 2px 5px;
    font-size: 12px;
    line-height: 15px;
    border-radius: 10px;
    margin-left: 5px;
  }
}

.popup{
  width: 610upx;
  height: 300upx;
  background: #fff;
  border-radius: 8upx;
  padding: 26upx 30upx;

  .mTitle{
    font-size: 30upx;
    padding-top: 3upx;
  }

  .bd{
    display: flex;
    font-size: 26upx;
    align-items: center;
    padding: 30upx 0;
  }

  .ft{
    display: flex;
    justify-content: end;
    padding: 30upx 0;
  }
  .btn{
    color: #05627b;
    text-align: center;
    margin-left: 50upx;
    font-size: 26upx;
  }
}
</style>
